<template>
  <a-table-summary fixed>
    <a-table-summary-row>
      <a-table-summary-cell>总计</a-table-summary-cell>
      <a-table-summary-cell v-for="cell in list" :index="cell.index" :key="cell.index" class="text-center">{{ cell.value }}</a-table-summary-cell>
    </a-table-summary-row>
  </a-table-summary>
</template>

<script setup lang="ts">
import { watch, ref } from 'vue'
import type { SummaryItem } from '@/model/table'

interface SummaryProps {
  dataSource: Array<SummaryItem>,
  columns: any
}

const list = ref<Array<SummaryItem>>([])

const props = withDefaults(defineProps<SummaryProps>(), {
  dataSource: () => [],
  columns: () => []
})

watch(
  () => props.dataSource,
  (val) => {
    function flatten (arr): any {
      let res: any = []
      arr.forEach(item => {
        if (item.children && item.children.length > 0) {
          res = res.concat(flatten(item.children))
        } else {
          res.push(item)
        }
      })
      return res
    }
   const flatColumns = flatten(props.columns.slice(1))
   list.value = flatColumns.map((column, index) => {
      const value = val.find(f => f.key == column.dataIndex)?.value ?? ''
      return {
        index: index + 1,
        value
      }
    })
  },
  {
    immediate: true,
  }
)
</script>

<style lang="less">
.ant-table-summary {
  tr {
    .ant-table-cell {
      padding: 10px 0 10px 8px;
    }
  }
}
</style>
